<template>
  <div class="select-tree-container">
    <el-select style="width: 100%" :disabled="disabled" v-model="id">
      <el-tree
        :data="treeDatas"
        node-key="id"
        auto-expand-parent
        :default-expand-all="treeExpandAll"
        :expand-on-click-node="false"
      >
        <template slot-scope="{ data }">
          <el-option
            :key="data.id"
            style="width: 100%"
            :value="data.id"
            :label="data.catalogName"
          />
        </template>
      </el-tree>
    </el-select>
  </div>
</template>
<script>
export default {
  name: "SelectTree",
  props: {
    modelValue: {
      type: [Number, String, Function],
      default: () => null,
    },
    defaultValue: {
      type: [Number, String, Function],
      default: () => null,
    },
    dataFun: {
      type: Function,
      default: () => null,
    },
    expandAll: {
      type: Boolean,
      default: () => true,
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
  },
  computed: {
    treeExpandAll: {
      get() {
        return this.expandAll;
      },
    },
  },
  watch: {
    id: {
      handler(val) {
        this.updateModelValue(val);
      },
    },
  },
  data() {
    return {
      treeDatas: [],
      id: null,
    };
  },
  async created() {
    this.$nextTick(async () => {
      await this.loadTreeData();
      if (!this.modelValue) {
        this.id = !Number(await this.defaultValue()) ? null : await this.defaultValue();
      } else {
        this.id = this.modelValue;
      }
    });
  },
  methods: {
    // 加载数据
    async loadTreeData() {
      const { data } = await this.dataFun();
      this.treeDatas = data;
    },

    // 选择数据
    updateModelValue(value) {
      this.$emit("update:modelValue", value);
    },
  },
};
</script>
<style lang="scss" scoped></style>
